package com.klaus.ohMySpace.controller;

import com.klaus.ohMySpace.conf.Constants;
import com.klaus.ohMySpace.entity.Admin;
import com.klaus.ohMySpace.service.AdminService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * Created by Mklaus on 15/8/16.
 */
@Controller
@RequestMapping("admin")
public class AdminController {
    @Resource
    private AdminService adminService;

    @RequestMapping(value = "login",method = RequestMethod.GET)
    public String login(){
        return "/admin/adminLogin";
    }

    @RequestMapping("doLogin")
    public String doLogin(String adminName,String password, Model model,HttpSession session){
        Admin login;
        if ((login = adminService.login(new Admin(adminName,password))) != null){
            session.setAttribute(Constants.ADMIN_UID,login.getId());
            model.addAttribute("admin",login);
            return "/admin/loginSuccess";
        }
        return "error";
    }

    @RequestMapping("logout")
    public String logout(HttpServletRequest req){
        req.getSession().removeAttribute(Constants.ADMIN_UID);
        return "redirect:/index.jsp";
    }

}
